package com.quplayer.qubrowser.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.quplayer.qubrowser.R;
import com.quplayer.qubrowser.adapters.WebPageAdapter;
import com.quplayer.qubrowser.base.BaseActivity;
import com.quplayer.qubrowser.entity.WebDeleteEvent;
import com.quplayer.qubrowser.entity.WebFragmentLoadBean;
import com.quplayer.qubrowser.fragments.WebViewFragment;
import com.quplayer.qubrowser.utils.DataFormatUtil;
import com.quplayer.qubrowser.utils.WebPageHelper;
import com.quplayer.qubrowser.widget.MyViewPager;
import com.quplayer.qubrowser.widget.webview.ZX5WebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 09/03/2019 22:51
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class BrowserActivity extends BaseActivity {


    @BindView(R.id.home_button)
    ImageView homeButton;
    @BindView(R.id.menu_button)
    ImageView menuButton;
    @BindView(R.id.query_button)
    TextView queryButton;
    @BindView(R.id.web_back)
    ImageView backButton;
    @BindView(R.id.web_freshen)
    ImageView freshenButton;
    @BindView(R.id.web_multi)
    ImageView multiButton;
    @BindView(R.id.web_next)
    ImageView nextButton;
    @BindView(R.id.web_stop_loading)
    ImageView stopLoading;

    @BindView(R.id.anchor)
    View anchor;
    @BindView(R.id.mtoolbar)
    View mtoolbar;

    @BindView(R.id.bottom_bar)
    View bottomBar;
    @BindView(R.id.web_page_control_bar)
    View webPageControlBackground;


    @BindView(R.id.web_container)
    MyViewPager mViewPager;
    @BindView(R.id.dot_indicator)
    LinearLayout indicator;

    private ZX5WebView webView;
    private WebPageAdapter webpageAdapter;
//    private MenuListAdapter menuAdapter;
    private long mExitTime;    //按下返回键退出时的时间
    private boolean first = true;  //有两种含义：第一次运行app时或标签页最后一页被删后需要重新定位当前WebView对象
    private boolean isZoom = false;  //是否缩放
    private SharedPreferences preferences;
    private int firstPosition = 0;
    private int selectMenuPosition = -2;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browser);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData(savedInstanceState);
    }

    public void initData(@Nullable Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);
        minitView(savedInstanceState);
    }

    private void minitView(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            List<Bundle> bundles = savedInstanceState.getParcelableArrayList("web_page_bundle");
            int count = savedInstanceState.getInt("web_page_count");
            for (int i = 0; i < count; i++) {
                WebViewFragment fragment = new WebViewFragment(bundles != null ? bundles.get(i) : null);
                WebPageHelper.webpagelist.add(fragment);
            }
            initDot(count);
        } else {
            String url = getIntent().getStringExtra("shortcut_url");
            Log.d("Main", "onCreate地址Path：" + url);
            WebViewFragment fragment = new WebViewFragment(null, url);
            WebPageHelper.webpagelist.add(fragment);
            initDot(1);
        }

        mViewPager.setOnLayoutClickListener(new MyViewPager.OnLayoutClickListener() {
            @Override
            public void onLayoutClick() {
                zoomChange(1);
            }
        });
        ((ViewGroup) mViewPager.getParent()).setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return mViewPager.dispatchTouchEvent(event);
            }
        });
        mViewPager.setPageMargin(DataFormatUtil.setDip2px(this, 45));
        webpageAdapter = new WebPageAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(webpageAdapter);

        mViewPager.setOffscreenPageLimit(5);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicator.getChildAt(firstPosition).setEnabled(false);
                indicator.getChildAt(position).setEnabled(true);
                firstPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    private void initDot(int count) {
        indicator.removeAllViews();
        View view;
        for (int i = 0; i < count; i++) {
            //创建底部指示器(小圆点)
            view = new View(this);
            view.setBackgroundResource(R.drawable.dot_background);
            view.setEnabled(false);
            //设置宽高
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DataFormatUtil.setDip2px(this, 7), DataFormatUtil.setDip2px(this, 7));
            //设置间隔
            if (i != 0) {
                layoutParams.leftMargin = DataFormatUtil.setDip2px(this, 6);
            }
            //添加到LinearLayout
            indicator.addView(view, layoutParams);
        }
        indicator.getChildAt(mViewPager.getCurrentItem()).setEnabled(true);
        firstPosition = mViewPager.getCurrentItem();
    }

    private void zoomChange(int flag) {
        //0为缩小，1为放大
        if (flag == 0) {
            isZoom = true;
            for (WebViewFragment webViewFragment : WebPageHelper.webpagelist) {
                webViewFragment.getInnerWebView().onPause();
                webViewFragment.getInnerWebView().pauseTimers();
            }
            webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            mViewPager.setFullScreen(false);
            mViewPager.clearAnimation();
            mViewPager.animate().scaleX(0.65f).scaleY(0.65f).setDuration(400).start();
            webPageControlBackground.setVisibility(View.VISIBLE);
            mtoolbar.setVisibility(View.INVISIBLE);
            bottomBar.setVisibility(View.INVISIBLE);
            indicator.setVisibility(View.VISIBLE);

        } else {
            //防止viewpager滑动错位
            fixWebPage(mViewPager.getCurrentItem());

            webView = WebPageHelper.webpagelist.get(mViewPager.getCurrentItem()).getInnerWebView(); //定位当前的WebView对象
            webView.setLayerType(View.LAYER_TYPE_NONE, null);
            isZoom = false;

            for (WebViewFragment webViewFragment : WebPageHelper.webpagelist) {
                if (WebPageHelper.webpagelist.get(mViewPager.getCurrentItem()).equals(webViewFragment)) {
                    webView.onResume();     //由于调用onResume会导致所有WebView都处于活动状态，而onPause只是针对单个
                    webView.resumeTimers();
                } else {
                    webViewFragment.getInnerWebView().onPause();
                    webViewFragment.getInnerWebView().pauseTimers();
                }
            }
            mViewPager.setFullScreen(true);

            mViewPager.clearAnimation();
            mViewPager.animate().scaleX(1f).scaleY(1f).setDuration(0).start();

            webPageControlBackground.setVisibility(View.INVISIBLE);
            mtoolbar.setVisibility(View.VISIBLE);
            bottomBar.setVisibility(View.VISIBLE);
            indicator.setVisibility(View.INVISIBLE);
            //检测当前的webview对象是否可以向前或前后浏览
            if (!webView.canGoBack()) {
                backButton.setEnabled(false);
            } else {
                backButton.setEnabled(true);
            }
            if (!webView.canGoForward()) {
                nextButton.setEnabled(false);
            } else {
                nextButton.setEnabled(true);
            }

        }
    }
    private void fixWebPage(int position) {
        webpageAdapter.notifyDataSetChanged();
        mViewPager.setCurrentItem(position, true);
    }
    @Override
    protected void onStop() {
        super.onStop();
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    if (!webView.getUrl().equals(data.getStringExtra("currentUri"))) {
                        webView.loadUrl(data.getStringExtra("currentUri"));
                    }
                }
                break;
        }
    }

    @OnClick({R.id.menu_button, R.id.query_button, R.id.web_back, R.id.web_next,
            R.id.web_freshen, R.id.web_stop_loading, R.id.web_multi, R.id.add_web_page,
            R.id.home_button,R.id.add_web_goback})
    public void onClick(View view) {
//        if (mDrawerLayout.isDrawerOpen(Gravity.START)) mDrawerLayout.closeDrawers();
        int object = view.getId();
        switch (object) {

            case R.id.add_web_goback:
                zoomChange(1);
                break;
            case R.id.web_back:
                webView.goBack();
                break;
            case R.id.web_next:
                webView.goForward();
                break;
            case R.id.web_freshen:
                webView.reload();
                break;
            case R.id.web_stop_loading:
                webView.stopLoading();
                break;
            case R.id.web_multi:
                zoomChange(0);
                break;
            case R.id.add_web_page:
                if (WebPageHelper.webpagelist.size() >= WebPageHelper.WEB_PAGE_LIMIT_NUM) {
                    Toast.makeText(this, "窗口数量超过最大值", Toast.LENGTH_SHORT).show();
                } else {
                    WebViewFragment fragment = new WebViewFragment(null);
                    WebPageHelper.webpagelist.add(mViewPager.getCurrentItem() + 1, fragment);
                    webpageAdapter.notifyDataSetChanged();
                    initDot(WebPageHelper.webpagelist.size());
                    fixWebPage(mViewPager.getCurrentItem() + 1);
                    zoomChange(1);
                }
                break;
            case R.id.home_button:
                webView.loadUrl("file:///android_asset/index.html");
                break;
            default:
                Toast.makeText(this, "开发中...", Toast.LENGTH_SHORT).show();

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetWebView(ZX5WebView webView){
        if (first) {
            //调用代表为新添加的webview
            BrowserActivity.this.webView = webView;
            first = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPageStarted(String url){
        backButton.setEnabled(false);
        nextButton.setEnabled(false);
        freshenButton.setVisibility(View.INVISIBLE);
        stopLoading.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onProgressChanged(Integer progress){
        if (progress > 80) {
            //进度大于80，一般网页就加载完成了,但是为了能够在点击收藏标签前收到icon，必须等到加载完成到100

            freshenButton.setVisibility(View.VISIBLE);
            stopLoading.setVisibility(View.INVISIBLE);
            if (!webView.canGoBack()) {
                backButton.setEnabled(false);
            } else {
                backButton.setEnabled(true);
            }
            if (!webView.canGoForward()) {
                nextButton.setEnabled(false);
            } else {
                nextButton.setEnabled(true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebFragmentLoad(WebFragmentLoadBean loadBean){
        WebViewFragment fragment = new WebViewFragment(null, loadBean.getUrl());
        WebPageHelper.webpagelist.add(mViewPager.getCurrentItem() + 1, fragment);
        webpageAdapter.notifyDataSetChanged();
        initDot(WebPageHelper.webpagelist.size());
        if (loadBean.getLoadInMode()==WebViewFragment.LOAD_IN_NEW_WINDOW){
            mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebFragmentDelete(WebDeleteEvent event) {
        //删除动画
        int viewTop = event.getViewTop();
        int value;
        if (viewTop > 0) {
            value = 2500;
        } else {
            value = -2500;
        }
        View selectedView = WebPageHelper.webpagelist.get(mViewPager.getCurrentItem()).getInnerContainer();
        Animation animation = new TranslateAnimation(0, 0, viewTop, value);
        animation.setDuration(400);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) { }

            @Override
            public void onAnimationEnd(Animation animation) {

                WebPageHelper.webpagelist.remove(mViewPager.getCurrentItem());
                webpageAdapter.notifyDataSetChanged();
                if (WebPageHelper.webpagelist.size() == 0) {
                    first = true;
                    WebViewFragment fragment = new WebViewFragment(null);
                    WebPageHelper.webpagelist.add(fragment);
                    webpageAdapter.notifyDataSetChanged();
                    zoomChange(1);
                }
                initDot(WebPageHelper.webpagelist.size());
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        selectedView.startAnimation(animation);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        List<WebViewFragment> webpagelist = WebPageHelper.webpagelist;
        for (WebViewFragment w:webpagelist){
            w.getInnerWebView().destroy();
        }
        super.onDestroy();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.hideCustomView()) {
                return true;
            } else if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
